package com.hls.mybatis.core;

import java.lang.annotation.Annotation;
import java.util.Arrays;
import java.util.Set;

import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.core.type.filter.AnnotationTypeFilter;

import com.hls.mybatis.core.annotation.Mybatis;

public class BeanScanner extends ClassPathBeanDefinitionScanner {

    public BeanScanner(BeanDefinitionRegistry registry, Class<? extends Annotation> annotation) {
        // TODO Auto-generated constructor stub
        super(registry,false);
        addIncludeFilter(new AnnotationTypeFilter(annotation));
        if (!Mybatis.class.equals(annotation)) {
            addIncludeFilter(new AnnotationTypeFilter(Mybatis.class));
        }
    }
    
    @Override
    protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
        Set<BeanDefinitionHolder> beanDefinitions = super.doScan(basePackages);

        if (beanDefinitions.isEmpty()) {
            logger.warn("No Dao interface was found in '" + Arrays.toString(basePackages) + "' package. Please check your configuration.");
        }
        GenericBeanDefinition definition;
        for (BeanDefinitionHolder holder : beanDefinitions) {
            definition = (GenericBeanDefinition) holder.getBeanDefinition();
            definition.getPropertyValues().add("proxy", getRegistry().getBeanDefinition("myHandler"));
            definition.getPropertyValues().add("daoInterface", definition.getBeanClassName());
            System.out.println("dynamic bean class:" + definition.getBeanClassName());
            definition.setBeanClass(MyFactoryBean.class);
        }
        return beanDefinitions;
    }
    
    /**
     * 默认不允许接口的,这里重写,覆盖下,另外默认会Scan @Component 这样所以的被@Component 注解的都会Scan
     */
    @Override
    protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
        return beanDefinition.getMetadata().isInterface() && beanDefinition.getMetadata().isIndependent();
    }
}
